package com.zw.pdm.module.report.service;

import com.zw.pdm.constant.Constant;
import com.zw.pdm.entity.basic.Org;
import com.zw.pdm.entity.basic.Verify;
import com.zw.pdm.entity.rep.Change;
import com.zw.pdm.entity.rep.Plan;
import com.zw.pdm.entity.rep.Sheet;
import com.zw.pdm.entity.rep.VerifyProcess;
import com.zw.pdm.entity.sys.User;
import com.zw.pdm.module.basic.mapper.OrgMapper;
import com.zw.pdm.module.basic.mapper.VerifyMapper;
import com.zw.pdm.module.basic.repository.OrgRepository;
import com.zw.pdm.module.report.mapper.ChangeMapper;
import com.zw.pdm.module.report.mapper.PlanMapper;
import com.zw.pdm.module.report.mapper.SheetMapper;
import com.zw.pdm.module.report.mapper.VerifyProcessMapper;
import com.zw.pdm.module.report.repository.ChangeRepository;
import com.zw.pdm.module.report.repository.PlanRepository;
import com.zw.pdm.module.report.repository.SheetRepository;
import com.zw.pdm.module.report.repository.VerifyProcessRepository;
import com.zw.pdm.module.system.service.LogService;
import com.zw.pdm.util.CommonUtils;
import com.zw.pdm.util.FileUtils;
import com.zw.pdm.util.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import static com.zw.pdm.constant.Constant.STATUS_COMMIT;
import static com.zw.pdm.util.BeanUtil.copy;


/**
 * @Description:
 *
 * @Author: China.sgl
 * @Date: 2019/12/6 08:42
 */
@Service
@SuppressWarnings("all")
public class ReportListService {

    @Autowired
    private SheetMapper sheetMapper;
    @Autowired
    private SheetRepository sheetRepository;
    @Autowired
    private PlanMapper planMapper;
    @Autowired
    private PlanRepository planRepository;
    @Autowired
    private OrgRepository orgRepository;
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private VerifyMapper verifyMapper;
    @Autowired
    private VerifyProcessRepository verifyProcessRepository;
    @Autowired
    private VerifyProcessMapper verifyProcessMapper;
    @Autowired
    private ChangeRepository changeRepository;
    @Autowired
    private ChangeMapper changeMapper;

    @Value("${user.upload.path}")
    private String uploadPath;

    @Autowired
    private LogService logService;

    /** 提报计划提交 列表 */
    public List<Sheet> findWithReportList(Sheet sheet, Integer i) {
        sheet.setPostUserId(ShiroUtils.getUserId());
        if (i == 1) {
            return sheetMapper.findEqIdWithReportList(sheet);
        } else {
            return sheetMapper.findInIdWithReportList(sheet);
        }
    }

    /**
     * 按ID删除计划单及其明细
     * 如果删除的为变更单，则原变更计划可再次变更。
     */
    public int delSheetById(Integer id) {
        logService.saveLog("删除计划单", "计划单ID：" + id);
        Sheet sheet = sheetRepository.getOne(id);
        if (sheet.getSheetType() == 2) {
            List<Change> changes = changeMapper.findBySheetId(id);
            for (Change change : changes) {
                if (change.getChangeId() != null) {
                    Change c = changeRepository.getOne(change.getChangeId());
                    c.setAlreadyChange(0);
                    changeRepository.saveAndFlush(c);
                } else if(change.getPlanId() != null) {
                    Plan p = planRepository.getOne(change.getPlanId());
                    p.setAlreadyChange(0);
                    planRepository.saveAndFlush(p);
                }
            }
            changeMapper.updateStatusBySheetId(id, Constant.STATUS_DELETE);
        } else if (sheet.getSheetType() == 1) {
            planMapper.updateStatusBySheetId(id, Constant.STATUS_DELETE);
        }
        return sheetMapper.updateStatusById(id, Constant.STATUS_DELETE);
    }

    /** 提交计划单 */
    @Transactional(rollbackFor = Exception.class)
    public int commitSheetById(Integer id) {
        logService.saveLog("提交计划单", "计划单ID：" + id);
        Sheet sheet = sheetRepository.getOne(id);

        sheet.setCommitTime(new Date());
        sheetRepository.saveAndFlush(sheet);

        if (sheet.getStatus() == STATUS_COMMIT) {
            return 1;
        }
        // 查询审核配置
        Verify verify = new Verify();
        verify.setReportType(sheet.getReportType());
        List<Verify> verifyList = verifyMapper.findByCondition(verify);
        // 生成审核记录
        for (int i = 0; i < verifyList.size(); i++) {
            VerifyProcess vp = new VerifyProcess();
            vp.setSheetId(sheet.getId());
            vp.setOrderNo(verifyList.get(i).getOrderNo());
            vp.setComp(verifyList.get(i).getComp());
            if (i == 0) {
                vp.setCur(1);
                vp.setStart(1);
            } else {
                vp.setCur(0);
                vp.setStart(0);
            }
            vp.setStatus(1);
            vp.setVerifier(verifyMapper.findVerifier(ShiroUtils.getUserId(), verifyList.get(i).getPost()));
            verifyProcessRepository.save(vp);
        }
        return sheetMapper.updateStatusAndRejectReasonById(id, null, STATUS_COMMIT);
    }

    /** 按ID删除计划 */
    public int delPlanById(Integer id) {
        logService.saveLog("删除计划", "计划ID" + id);
        return planMapper.updateStatusById(id, Constant.STATUS_DELETE);
    }

    /** 上传计划附件 */
    public Plan uploadWithPlan(Plan plan, MultipartFile file) {
        if (null != file) {
            Plan p = planRepository.getOne(plan.getId());
            plan.setUploadTime(new Date());
            StringBuffer pathPart = new StringBuffer();
            pathPart.append(p.getSheetId());
            pathPart.append("/");
            pathPart.append(p.getId());
            pathPart.append("/");
            String fileName = FileUtils.upload(file, uploadPath + pathPart.toString());
            if (CommonUtils.isNotNull(fileName)) {
                p.setUrl("/files/" + pathPart.toString() + fileName);
                logService.saveLog("上传附件", "名称：" + fileName);
                return planRepository.saveAndFlush(p);
            }
        }
        return null;
    }

    /** 修改外购件计划单 */
    public int editOut(Sheet sheet, Integer[] planId, String[] malDesc, Double[] num, String[] unit, String[] standard, String[] brand, String[] remark) {
        Sheet target = sheetRepository.getOne(sheet.getId());
        target.setPostTel(sheet.getPostTel());
        target.setMalType(sheet.getMalType());
        target.setPart(sheet.getPart());
        target.setSpecial(sheet.getSpecial());
        sheetRepository.saveAndFlush(target);
        for (int i = 0; i < planId.length; i++) {
            Plan plan = planRepository.getOne(planId[i]);
            plan.setMalDesc(malDesc[i]);
            plan.setNum(num[i]);
            plan.setUnit(unit[i]);
            if (standard.length > 0) {
                plan.setStandard(standard[i]);
            }
            if (brand.length > 0) {
                plan.setBrand(brand[i]);
            }
            if (remark.length > 0) {
                plan.setRemark(remark[i]);
            }
            planRepository.saveAndFlush(plan);
        }
        logService.saveLog("修改外购件计划单", "计划单ID：" + sheet.getId());
        return 1;
    }

    /** 修改外协计划单 */
    public int editAss(Sheet sheet, Integer[] planId, String[] malDesc, String[] diagram, Double[] num, String[] unit, String[] assistType, String[] remark) {
        Sheet target = sheetRepository.getOne(sheet.getId());
        target.setPostTel(sheet.getPostTel());
        target.setMalType(sheet.getMalType());
        target.setPart(sheet.getPart());
        sheetRepository.saveAndFlush(target);
        for (int i = 0; i < planId.length; i++) {
            Plan plan = planRepository.getOne(planId[i]);
            plan.setMalDesc(malDesc[i]);
            if (diagram.length > 0) {
                plan.setDiagram(diagram[i]);
            }
            plan.setNum(num[i]);
            plan.setUnit(unit[i]);
            plan.setAssistType(assistType[i]);
            if (remark.length > 0) {
                plan.setRemark(remark[i]);
            }
            planRepository.saveAndFlush(plan);
        }
        logService.saveLog("修改外协件计划单", "计划单ID：" + sheet.getId());
        return 1;
    }

    /** 修改原料计划单 */
    public int editMal(Sheet sheet, Integer[] planId, String[] malDesc, Double[] num, String[] unit, String[] standard, String[] quality, String[] useStore, String[] remark) {
        Sheet target = sheetRepository.getOne(sheet.getId());
        target.setMalType(sheet.getMalType());
        target.setPostTel(sheet.getPostTel());
        target.setPart(sheet.getPart());
        sheetRepository.saveAndFlush(target);
        for (int i = 0; i < planId.length; i++) {
            Plan plan = planRepository.getOne(planId[i]);
            plan.setMalDesc(malDesc[i]);
            plan.setNum(num[i]);
            plan.setUnit(unit[i]);
            if (standard.length > 0) {
                plan.setStandard(standard[i]);
            }
            if (quality.length > 0) {
                plan.setQuality(quality[i]);
            }
            if (useStore.length > 0) {
                plan.setUseStore("是".equals(useStore[i]) ? 1 : 0);
            } else {
                plan.setUseStore(0);
            }
            if (remark.length > 0) {
                plan.setRemark(remark[i]);
            }
            planRepository.save(plan);
        }
        logService.saveLog("修改原材料计划单", "计划单ID：" + sheet.getId());
        return 1;
    }

    /** 按 IDS 查询计划 */
    public List<Plan> findPlanByIds(String ids) {
        return planMapper.findByIds(ids);
    }

    /** 按 IDS 查询变更 */
    public List<Change> findChangeByIds(String ids) {
        return changeMapper.findByIds(ids);
    }

    /** 生成变更批次号 */
    private void genChangeBatchNo(Sheet sheet) {
        Sheet st = sheetMapper.findChangeFirstByBatchNo(sheet.getProCode());
        if (st == null) {
            sheet.setBatchNo(sheet.getProCode() + "R001");
        } else {
            int no = Integer.parseInt(CommonUtils.substring(st.getBatchNo(), st.getProCode().length() + 1));
            sheet.setBatchNo(sheet.getProCode() + "R" + CommonUtils.intToString(no+1, 3));
        }
    }

    /** 生成变更计划单 */
    private Sheet genChangeSheet(Sheet st) {
        Sheet sheet = sheetRepository.getOne(st.getId());
        User user = ShiroUtils.getUser();
        Sheet target = new Sheet();
        copy(sheet, target);
        target.setId(null);
        target.setStatus(1);
        target.setSheetType(2);
        target.setMayChange(0);
        target.setRawSplit(0);
        target.setLssueStatus(1);
        target.setSheetId(st.getId());
        target.setPostTel(st.getPostTel());
        target.setPostUserId(user.getId());
        target.setPostName(user.getName());
        target.setDept(user.getDept());
        target.setDeptId(user.getDeptId());
        target.setBranchName(user.getBranchName());
        target.setCommitTime(null);
        target.setRawSplit(0);
        Org dept = orgRepository.getOne(ShiroUtils.getUser().getOrgId());
        if (dept != null) {
            target.setPostDept(dept.getName());
        }
        target.setCreateTime(new Date());
        genChangeBatchNo(target);
        return sheetRepository.save(target);
    }

    /** 保存外购件变更计划单 */
    @Transactional(rollbackFor = Exception.class)
    public int saveOutChange(Sheet st, String[] changeReason, Integer[] planId, String[] afterMalDesc, Double[] afterNum, String[] afterUnit, String[] afterStandard, String[] afterBrand, String[] afterRemark, String[] afterUrl) {
        Sheet sheet = genChangeSheet(st);
        Sheet src = sheetRepository.getOne(st.getId());
        logService.saveLog("外购件计划单变更", "原计划单ID：" + src.getId() + " 新计划单ID：" + sheet.getId());

        for (int i = 0; i < planId.length; i++) {
            Change change = new Change();
            if (src.getSheetType() == 1) {
                Plan plan = planRepository.getOne(planId[i]);
                plan.setAlreadyChange(1);
                planRepository.saveAndFlush(plan);
                copy(plan, change);
                change.setPlanId(plan.getId());
            } else if (src.getSheetType() == 2) {
                Change c = changeRepository.getOne(planId[i]);
                c.setAlreadyChange(1);
                changeRepository.saveAndFlush(c);
                change.setMalDesc(c.getAfterMalDesc());
                change.setNum(c.getAfterNum());
                change.setUnit(c.getAfterUnit());
                change.setStandard(c.getAfterStandard());
                change.setBrand(c.getAfterBrand());
                change.setRemark(c.getAfterRemark());
                change.setUrl(c.getAfterUrl());
                change.setDiagram(c.getAfterDiagram());
                change.setUseStore(c.getAfterUseStore());
                change.setAssistType(c.getAfterAssistType());
                change.setPlanId(c.getPlanId());
                change.setChangeId(c.getId());
            }
            change.setId(null);
            change.setAlreadyChange(0);
            change.setSheetId(sheet.getId());
            change.setCreateTime(new Date());
            change.setStatus(Constant.STATUS_NORMAL);
            change.setAfterMalDesc(afterMalDesc[i]);
            change.setAfterNum(afterNum[i]);
            change.setAfterUnit(afterUnit[i]);
            if (afterStandard.length > 0) {
                change.setAfterStandard(afterStandard[i]);
            }
            if (afterBrand.length > 0) {
                change.setAfterBrand(afterBrand[i]);
            }
            if (afterRemark.length > 0) {
                change.setAfterRemark(afterRemark[i]);
            }
            change.setChangeReason(changeReason[i]);
            change = changeRepository.save(change);
            if (afterUrl.length > 0 && CommonUtils.isNotEmpty(afterUrl[i])) {
                StringBuffer dir = new StringBuffer();
                dir.append(uploadPath).append(sheet.getId()).append("/c/").append(change.getId()).append("/");
                try {
                    org.apache.commons.io.FileUtils.moveToDirectory(new File(afterUrl[i]), new File(dir.toString()), true);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                StringBuffer srcPart = new StringBuffer();
                srcPart.append(uploadPath).append(ShiroUtils.getLoginName()).append("/temp/");
                StringBuffer targetPart = new StringBuffer();
                targetPart.append("/files/").append(sheet.getId()).append("/c/").append(change.getId()).append("/");
                change.setAfterUrl(afterUrl[i].replace(srcPart.toString(), targetPart.toString()));
                change.setUploadTime(new Date());
                changeRepository.save(change);
            }
        }
        return 1;
    }

    /** 保存外协件变更计划单 */
    @Transactional
    public int saveAssChange(Sheet st, String[] changeReason, Integer[] planId, String[] afterMalDesc, String[] afterDiagram, Double[] afterNum, String[] afterUnit, String[] afterAssistType, String[] afterRemark, String[] afterUrl) {
        Sheet sheet = genChangeSheet(st);
        Sheet src = sheetRepository.getOne(st.getId());
        logService.saveLog("外协件计划单变更", "原计划单ID：" + src.getId() + " 新计划单ID：" + sheet.getId());

        for (int i = 0; i < planId.length; i++) {
            Change change = new Change();
            if (src.getSheetType() == 1) {
                Plan plan = planRepository.getOne(planId[i]);
                plan.setAlreadyChange(1);
                planRepository.saveAndFlush(plan);
                copy(plan, change);
                change.setPlanId(plan.getId());
            } else if (src.getSheetType() == 2) {
                Change c = changeRepository.getOne(planId[i]);
                c.setAlreadyChange(1);
                changeRepository.saveAndFlush(c);
                change.setMalDesc(c.getAfterMalDesc());
                change.setNum(c.getAfterNum());
                change.setUnit(c.getAfterUnit());
                change.setStandard(c.getAfterStandard());
                change.setBrand(c.getAfterBrand());
                change.setRemark(c.getAfterRemark());
                change.setUrl(c.getAfterUrl());
                change.setDiagram(c.getAfterDiagram());
                change.setUseStore(c.getAfterUseStore());
                change.setAssistType(c.getAfterAssistType());
                change.setPlanId(c.getPlanId());
                change.setChangeId(c.getId());
            }
            change.setId(null);
            change.setAlreadyChange(0);
            change.setSheetId(sheet.getId());
            change.setCreateTime(new Date());
            change.setStatus(Constant.STATUS_NORMAL);
            change.setAfterMalDesc(afterMalDesc[i]);
            change.setAfterNum(afterNum[i]);
            change.setAfterUnit(afterUnit[i]);
            if (afterDiagram.length > 0) {
                change.setAfterDiagram(afterDiagram[i]);
            }
            if (afterAssistType.length > 0) {
                change.setAfterAssistType(afterAssistType[i]);
            }
            if (afterRemark.length > 0) {
                change.setAfterRemark(afterRemark[i]);
            }
            change.setChangeReason(changeReason[i]);
            change = changeRepository.save(change);
            if (afterUrl.length > 0 && CommonUtils.isNotEmpty(afterUrl[i])) {
                StringBuffer dir = new StringBuffer();
                dir.append(uploadPath).append(sheet.getId()).append("/c/").append(change.getId()).append("/");
                try {
                    org.apache.commons.io.FileUtils.moveToDirectory(new File(afterUrl[i]), new File(dir.toString()), true);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                StringBuffer srcPart = new StringBuffer();
                srcPart.append(uploadPath).append(ShiroUtils.getLoginName()).append("/temp/");
                StringBuffer targetPart = new StringBuffer();
                targetPart.append("/files/").append(sheet.getId()).append("/c/").append(change.getId()).append("/");
                change.setAfterUrl(afterUrl[i].replace(srcPart.toString(), targetPart.toString()));
                change.setUploadTime(new Date());
                changeRepository.save(change);
            }
        }
        return 1;
    }

    /** 保存原材料变更计划单 */
    @Transactional
    public int saveMalChange(Sheet st, String[] changeReason, Integer[] planId, String[] afterMalDesc, Double[] afterNum, String[] afterUnit, String[] afterStandard, String[] afterQuality, String[] afterUseStore, String[] afterRemark, String[] afterUrl) {
        Sheet sheet = genChangeSheet(st);
        Sheet src = sheetRepository.getOne(st.getId());
        logService.saveLog("原材料计划单变更", "原计划单ID：" + src.getId() + " 新计划单ID：" + sheet.getId());

        for (int i = 0; i < planId.length; i++) {
            Change change = new Change();
            if (src.getSheetType() == 1) {
                Plan plan = planRepository.getOne(planId[i]);
                plan.setAlreadyChange(1);
                planRepository.saveAndFlush(plan);
                copy(plan, change);
                change.setPlanId(plan.getId());
            } else if (src.getSheetType() == 2) {
                Change c = changeRepository.getOne(planId[i]);
                c.setAlreadyChange(1);
                changeRepository.saveAndFlush(c);
                change.setMalDesc(c.getAfterMalDesc());
                change.setNum(c.getAfterNum());
                change.setUnit(c.getAfterUnit());
                change.setStandard(c.getAfterStandard());
                change.setQuality(c.getAfterQuality());
                change.setBrand(c.getAfterBrand());
                change.setRemark(c.getAfterRemark());
                change.setUrl(c.getAfterUrl());
                change.setDiagram(c.getAfterDiagram());
                change.setUseStore(c.getAfterUseStore());
                change.setAssistType(c.getAfterAssistType());
                change.setPlanId(c.getPlanId());
                change.setChangeId(c.getId());
            }
            change.setId(null);
            change.setAlreadyChange(0);
            change.setSheetId(sheet.getId());
            change.setCreateTime(new Date());
            change.setStatus(Constant.STATUS_NORMAL);
            change.setAfterMalDesc(afterMalDesc[i]);
            change.setAfterNum(afterNum[i]);
            change.setAfterUnit(afterUnit[i]);
            if (afterStandard.length > 0) {
                change.setAfterStandard(afterStandard[i]);
            }
            if (afterQuality.length > 0) {
                change.setAfterQuality(afterQuality[i]);
            }
            if (afterUseStore.length > 0) {
                change.setAfterUseStore("是".equals(afterUseStore[i]) ? 1 : 0);
            }else {
                change.setAfterUseStore(0);
            }
            if (afterRemark.length > 0) {
                change.setAfterRemark(afterRemark[i]);
            }
            change.setChangeReason(changeReason[i]);
            change = changeRepository.save(change);
            if (afterUrl.length > 0 && CommonUtils.isNotEmpty(afterUrl[i])) {
                StringBuffer dir = new StringBuffer();
                dir.append(uploadPath).append(sheet.getId()).append("/c/").append(change.getId()).append("/");
                try {
                    org.apache.commons.io.FileUtils.moveToDirectory(new File(afterUrl[i]), new File(dir.toString()), true);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                StringBuffer srcPart = new StringBuffer();
                srcPart.append(uploadPath).append(ShiroUtils.getLoginName()).append("/temp/");
                StringBuffer targetPart = new StringBuffer();
                targetPart.append("/files/").append(sheet.getId()).append("/c/").append(change.getId()).append("/");
                change.setAfterUrl(afterUrl[i].replace(srcPart.toString(), targetPart.toString()));
                change.setUploadTime(new Date());
                changeRepository.save(change);
            }
        }
        return 1;
    }

    /** 按ID删除变更计划 */
    public int delChangeById(Integer id) {
        return changeMapper.delById(id);
    }

    /** 上传变更计划附件 */
    public Change uploadWithChange(Change change, MultipartFile file) {
        if (null != file) {
            Change p = changeRepository.getOne(change.getId());
            StringBuffer sb = new StringBuffer();
            sb.append(uploadPath);
            sb.append(p.getSheetId());
            sb.append("/c/");
            sb.append(p.getId());
            sb.append("/");
            String fileName = FileUtils.upload(file, sb.toString());
            if (CommonUtils.isNotNull(fileName)) {
                StringBuffer url = new StringBuffer();
                url.append("/files/");
                url.append(p.getSheetId());
                url.append("/c/");
                url.append(p.getId());
                url.append("/");
                url.append(fileName);
                p.setAfterUrl(url.toString());
                logService.saveLog("上传附件", "名称：" + fileName);
                return changeRepository.saveAndFlush(p);
            }
        }
        return null;
    }

    /** 修改外购件变更计划单 */
    @Transactional
    public int editOutChange(Sheet st, Integer[] planId, String[] changeReason, String[] afterMalDesc, Double[] afterNum, String[] afterUnit, String[] afterStandard, String[] afterBrand, String[] afterRemark) {
        Sheet sheet = sheetRepository.getOne(st.getId());
        sheet.setPostTel(st.getPostTel());
        sheetRepository.saveAndFlush(sheet);
        for (int i = 0; i < planId.length; i++) {
            Change change = changeRepository.getOne(planId[i]);
            change.setAfterMalDesc(afterMalDesc[i]);
            change.setAfterNum(afterNum[i]);
            change.setAfterUnit(afterUnit[i]);
            if (afterStandard.length > 0) {
                change.setAfterStandard(afterStandard[i]);
            }
            if (afterBrand.length > 0) {
                change.setAfterBrand(afterBrand[i]);
            }
            if (afterRemark.length > 0) {
                change.setAfterRemark(afterRemark[i]);
            }
            change.setChangeReason(changeReason[i]);
            changeRepository.save(change);
        }
        logService.saveLog("修改外购件计划变更单", "计划单ID：" + sheet.getId());
        return 1;
    }

    /**
     * 修改外协件变更计划单
     */
    @Transactional
    public int editAssChange(Sheet st, Integer[] planId, String[] changeReason, String[] afterMalDesc, String[] afterDiagram, Double[] afterNum, String[] afterUnit, String[] afterAssistType, String[] afterRemark) {
        Sheet sheet = sheetRepository.getOne(st.getId());
        sheet.setPostTel(st.getPostTel());
        sheetRepository.saveAndFlush(sheet);
        for (int i = 0; i < planId.length; i++) {
            Change change = changeRepository.getOne(planId[i]);
            change.setAfterMalDesc(afterMalDesc[i]);
            change.setAfterNum(afterNum[i]);
            change.setAfterUnit(afterUnit[i]);
            if (afterDiagram.length > 0) {
                change.setAfterDiagram(afterDiagram[i]);
            }
            if (afterAssistType.length > 0) {
                change.setAfterAssistType(afterAssistType[i]);
            }
            if (afterRemark.length > 0) {
                change.setAfterRemark(afterRemark[i]);
            }
            change.setChangeReason(changeReason[i]);
            changeRepository.save(change);
        }
        logService.saveLog("修改外协件计划变更单", "计划单ID：" + sheet.getId());
        return 1;
    }

    /**
     * 修改原材料变更计划单
     */
    @Transactional
    public int editMalChange(Sheet st, Integer[] planId, String[] changeReason, String[] afterMalDesc, Double[] afterNum, String[] afterUnit, String[] afterStandard, String[] afterQuality, String[] afterUseStore, String[] afterRemark) {
        Sheet sheet = sheetRepository.getOne(st.getId());
        sheet.setPostTel(st.getPostTel());
        sheetRepository.saveAndFlush(sheet);
        for (int i = 0; i < planId.length; i++) {
            Change change = changeRepository.getOne(planId[i]);
            change.setAfterMalDesc(afterMalDesc[i]);
            change.setAfterNum(afterNum[i]);
            change.setAfterUnit(afterUnit[i]);
            if (afterStandard.length > 0) {
                change.setAfterStandard(afterStandard[i]);
            }
            if (afterQuality.length > 0) {
                change.setAfterQuality(afterQuality[i]);
            }
            if (afterUseStore.length > 0) {
                change.setAfterUseStore("是".equals(afterUseStore[i]) ? 1 : 0);
            } else {
                change.setAfterUseStore(0);
            }
            if (afterRemark.length > 0) {
                change.setAfterRemark(afterRemark[i]);
            }
            change.setChangeReason(changeReason[i]);
            changeRepository.save(change);
        }
        logService.saveLog("修改外购件计划变更单", "计划单ID：" + sheet.getId());
        return 1;
    }

    /** 按计划单ID查询计划 */
    public List<Plan> findPlanListBySheetId(Integer sheetId) {
        return planMapper.findBySheetId(sheetId);
    }

    /** 按计划单ID查询变更 */
    public List<Change> findChangeListBySheetId(Integer sheetId) {
        return changeMapper.findBySheetId(sheetId);
    }

    /** 查询管理部门数量 */
    public Integer countOrgByUserId() {
        return orgMapper.countOrgByUserId(ShiroUtils.getUserId());
    }

}
